package com.example.baimao_tp

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import java.util.Locale
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalConfiguration
import androidx.core.content.ContextCompat
import com.example.baimao_tp.ui.screen.CameraScreen
import com.example.baimao_tp.ui.screen.SettingsScreen
import com.example.baimao_tp.ui.theme.AIPoseTheme
import com.example.baimao_tp.utils.LocaleHelper
import com.example.baimao_tp.viewmodel.CameraViewModel
import androidx.lifecycle.viewmodel.compose.viewModel

class MainActivity : ComponentActivity() {
    private val requestCameraPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
            if (isGranted) {
                Toast.makeText(this, "相机权限已授予", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "相机权限被拒绝，无法使用拍照功能", Toast.LENGTH_LONG).show()
            }
        }

    private val requestStoragePermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
            if (isGranted) {
                Toast.makeText(this, "存储权限已授予", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "存储权限被拒绝，无法保存照片", Toast.LENGTH_LONG).show()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        // 初始化系统语言设置（必须在setContent之前）
        initializeSystemLanguage()

        // 检查权限
        checkAndRequestPermissions()

        setContent {
            AIPoseTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    val currentScreen = remember { mutableStateOf("camera") }
                    val viewModel: CameraViewModel = viewModel()
                    val context = LocalContext.current

                    // 添加一个语言key来强制重组
                    val languageKey = remember { mutableStateOf(0) }

                    // 监听语言变化并更新配置
                    LaunchedEffect(viewModel.selectedLanguage) {
                        Log.d("MainActivity", "语言变化，更新Configuration: ${viewModel.selectedLanguage}")

                        // 更新系统Locale
                        val newLocale = Locale(viewModel.selectedLanguage)
                        Locale.setDefault(newLocale)

                        // 更新应用配置
                        val config = Configuration(context.resources.configuration)
                        config.setLocale(newLocale)

                        // 更新资源配置
                        val resources = context.resources
                        val displayMetrics = resources.displayMetrics
                        resources.updateConfiguration(config, displayMetrics)

                        // 等待一小段时间确保配置更新完成
                        kotlinx.coroutines.delay(100)

                        // 强制触发界面重组
                        languageKey.value++

                        Log.d("MainActivity", "语言配置更新完成，触发重组: languageKey=${languageKey.value}")
                    }

                    when (currentScreen.value) {
                        "camera" -> CameraScreen(
                            onBack = {
                                finish()
                            },
                            onOpenSettings = {
                                currentScreen.value = "settings"
                                // 加载姿势配置
                                viewModel.loadPoseConfig(context)
                            }
                        )
                        "settings" -> SettingsScreen(
                            onBack = {
                                // 先应用筛选条件，然后再切换界面
                                Log.d("MainActivity", "从设置界面返回，开始应用筛选条件")
                                viewModel.generatePoses {
                                    // 在筛选条件应用完成后再切换界面
                                    currentScreen.value = "camera"

                                    Log.d("MainActivity", "筛选条件已应用，切换到拍照界面")
                                }
                            },
                            // 传递key来强制重组
                            languageKey = languageKey.value
                        )
                    }
                }
            }
        }
    }

    /**
     * 初始化系统语言设置
     */
    private fun initializeSystemLanguage() {
        // 获取系统默认语言
        val systemLanguage = getSystemLanguageCode()
        Log.d("MainActivity", "系统默认语言代码: $systemLanguage")

        // 更新应用语言配置
        updateAppLanguage(systemLanguage)

        // 强制更新Activity的配置
        updateActivityConfiguration(systemLanguage)
    }

    /**
     * 更新Activity配置
     */
    private fun updateActivityConfiguration(languageCode: String) {
        try {
            val locale = Locale(languageCode)
            val config = baseContext.resources.configuration
            config.setLocale(locale)

            // 创建新的Context并更新资源配置
            val updatedContext = createConfigurationContext(config)
            resources.updateConfiguration(config, resources.displayMetrics)

            Log.d("MainActivity", "Activity配置已更新为: $languageCode")
        } catch (e: Exception) {
            Log.e("MainActivity", "更新Activity配置失败: ${e.message}", e)
        }
    }

    /**
     * 获取系统语言代码
     */
    private fun getSystemLanguageCode(): String {
        Log.d("MainActivity", "=== MainActivity开始检测系统语言 ===")
        Log.d("MainActivity", "SDK版本: ${android.os.Build.VERSION.SDK_INT}")

        // 方法1：通过Resources获取
        val locale1 = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            resources.configuration.locales[0]
        } else {
            @Suppress("DEPRECATION")
            resources.configuration.locale
        }
        Log.d("MainActivity", "MainActivity方法1 - Resources: ${locale1.language}, 国家: ${locale1.country}, 显示名: ${locale1.displayName}")

        // 方法2：通过Locale.getDefault()获取
        val locale2 = Locale.getDefault()
        Log.d("MainActivity", "MainActivity方法2 - Locale.getDefault(): ${locale2.language}, 国家: ${locale2.country}, 显示名: ${locale2.displayName}")

        // 方法3：检查当前应用的Configuration
        val currentConfig = baseContext.resources.configuration
        val locale3 = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            currentConfig.locales[0]
        } else {
            @Suppress("DEPRECATION")
            currentConfig.locale
        }
        Log.d("MainActivity", "MainActivity方法3 - BaseContext: ${locale3.language}, 国家: ${locale3.country}, 显示名: ${locale3.displayName}")

        // 方法4：检查系统属性
        try {
            val languageProperty = java.lang.System.getProperty("user.language")
            val countryProperty = java.lang.System.getProperty("user.country")
            Log.d("MainActivity", "MainActivity方法4 - System属性: language=$languageProperty, country=$countryProperty")
        } catch (e: Exception) {
            Log.w("MainActivity", "无法获取系统属性: ${e.message}")
        }

        // 选择最可靠的检测结果
        // 优先使用ApplicationContext的语言配置，因为它能获取到正确的系统语言
        val selectedLocale = locale3
        Log.d("MainActivity", "选择使用BaseContext的语言检测结果")
        val languageCode = selectedLocale.language

        Log.d("MainActivity", "MainActivity最终选择的语言代码: $languageCode")
        Log.d("MainActivity", "MainActivity最终选择的国家代码: ${selectedLocale.country}")
        Log.d("MainActivity", "MainActivity最终语言的显示名: ${selectedLocale.displayName}")

        val resultLanguage = when {
            languageCode.startsWith("zh") -> "zh"  // 中文
            languageCode.startsWith("en") -> "en"  // 英文
            else -> "en"  // 默认英文
        }

        Log.d("MainActivity", "MainActivity映射后的语言代码: $resultLanguage")
        Log.d("MainActivity", "=== MainActivity系统语言检测完成 ===")

        return resultLanguage
    }

    /**
     * 更新应用语言配置
     */
    private fun updateAppLanguage(languageCode: String) {
        try {
            val newLocale = Locale(languageCode)
            Locale.setDefault(newLocale)

            val config = Configuration(resources.configuration)
            config.setLocale(newLocale)
            resources.updateConfiguration(config, resources.displayMetrics)

            Log.d("MainActivity", "应用语言已更新为: $languageCode")
        } catch (e: Exception) {
            Log.e("MainActivity", "更新语言配置失败: ${e.message}", e)
        }
    }

    private fun checkAndRequestPermissions() {
        val permissionsToRequest = mutableListOf<String>()

        // 检查相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.CAMERA)
        }

        // 检查存储权限 (Android 11 以下)
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.R) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }
        }

        // 请求权限
        if (permissionsToRequest.isNotEmpty()) {
            if (permissionsToRequest.size == 1) {
                // 单个权限
                if (permissionsToRequest.contains(Manifest.permission.CAMERA)) {
                    requestCameraPermissionLauncher.launch(Manifest.permission.CAMERA)
                } else {
                    requestStoragePermissionLauncher.launch(permissionsToRequest[0])
                }
            } else {
                // 多个权限 - 逐个请求
                requestCameraPermissionLauncher.launch(Manifest.permission.CAMERA)
            }
        }
    }
}